import styles from "./index.module.scss";
import { useEffect, useState } from "react";
import { InboxOutlined } from "@ant-design/icons";
import { Modal, message, Upload, Divider } from "antd";
import { uploadFile } from "@/service/file/index";
import { useDispatch, useSelector } from "react-redux";
import { availableAtion } from "@/store/createAction";
import emitter from "@/utils/eventEmitter";

const UploadDragger = (props) => {
  const dispatch = useDispatch();

  const searchParams = useSelector(
    (state) => state.searchReducer?.searchParams
  );

  const { Dragger } = Upload;

  const [fileList, setFileList] = useState([]);

  const [confirmLoading, setConfirmLoading] = useState(false);

  const beforeUpload = (file, files) => {
    if (files.length > 300) {
      message.error("文件数量过多，一次最多只能上传300个文件！");
      return false;
    }

    setFileList([...fileList, ...files]);
    return false;
  };
  
  const handleUpload = async () => {
    if (!fileList.length) {
      return message.info("请先选择文件");
    }

    emitter.emit("showUploadDrawer");

    let fileNames = "";
    const directoryPathMap = {};

    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append(`files`, file);
      fileNames += `、 ${file.name}`;
      if (file.webkitRelativePath) {
        directoryPathMap[file.name] = file.webkitRelativePath.replace(
          `/${file.name}`,
          ""
        );
      }
    });
    formData.append("path", searchParams["path"] || "");

    if (Object.keys(directoryPathMap).length) {
        formData.append("directoryPathMap", JSON.stringify(directoryPathMap));
    }

    message.info(`${fileNames.slice(1)} 正在拼命上传中`);
    // setConfirmLoading(true);

    props.setOpen(false);
    try {
      await uploadFile({ params: formData });
      message.success("文件上传成功");
      emitter.emit("refreshTaskList");
      dispatch(await availableAtion());
      props.refreshTable();
      // 上传成功后清空文件列表
      setFileList([]);
    } catch (err) {
      message.error("文件上传失败", err);
    } finally {
    //   setConfirmLoading(false);
    }
  };

  //   上传
  const handleOk = () => {
    handleUpload();
  };

  //   取消
  const handleCancel = () => {
    props.setOpen(false);
  };

  //   重置上传列表
  const resetFileList = () => {
    setFileList([]);
  };

  //   移除上传项
  const handleRemove = (file) => {
    const filterFileList = fileList.filter((item) => item.uid !== file.uid);
    setFileList(filterFileList);
  };

  useEffect(() => {
    if (!props.isOpen) {
      resetFileList();
    }
  }, [props.isOpen]);

  return (
    <Modal
      title={`上传${props.title}`}
      className={styles["ant-modal-content"]}
      open={props.isOpen}
      okText="上传"
      cancelText="取消"
      maskClosable={false}
      confirmLoading={confirmLoading}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <Dragger
        className={styles["dragger"]}
        fileList={fileList}
        multiple={true}
        directory={props.isDirectory}
        beforeUpload={beforeUpload}
        onRemove={handleRemove}
        {...props.uploadProps}
      >
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">单击或拖动{props.title}到此区域</p>
        {props.title === "文件" ? (
          <p className="ant-upload-hint">支持单次或批量上传。</p>
        ) : (
          ""
        )}
      </Dragger>
    </Modal>
  );
};

export default UploadDragger;
